#include "init_config.hpp"
#include "init_admin.hpp"

Init_Config::Init_Config()
{
  string file(FILE_CONFIG);
  FILE* config=fopen(file.c_str(),"r");
  char* line=NULL;
  size_t n;
  string key,information;

  string key_tab[]={"Net_Port","Name","File_Config","File_Log","Rcon_Pass"};
  string information_tab[NB_INSTRUCTION];
  bool verif_tab[NB_INSTRUCTION];

  for(int c=0 ; c < NB_INSTRUCTION ; ++c)
    verif_tab[c]=false;

  if(config != NULL)
    {
      fseek(config,0,SEEK_SET);

      while(getline(&line,&n,config) != -1)
	{
	  if(line[0] != '#' && line[0] != '\n')
	    {
	      unsigned int c(0);
	      key="";
	      information="";
	      
	      for( ; line[c] != ':' && line[c] != '\n' && c < n ; ++c)
		if(line[c] != ' ')
		  key+=line[c];

	      ++c;

	      for( ; line[c] != '\n' && c < n ; ++c)
		if(line[c] != ' ')
		  information+=line[c];

	      verif_key(key,information,verif_tab,information_tab,key_tab);
	    }

	  n=0;
	  free(line);
	  line=NULL;
	}

      free(line);
      line=NULL;

      fclose(config);

      for(int c(0) ; c < NB_INSTRUCTION ; ++c)
	cout << information_tab[c] << endl;

      send_cmd=new Send_Command("127.0.0.1",convert_to_unsigned_int(information_tab[0]),PORT_COM,information_tab[4]);
    }
  else
    cout << "ERROR folder file config" << endl;
}

void Init_Config::verif_key(string key,string information,bool verif_tab[],string tab_information[],string tab_key[])
{
  bool find(false);

  for(unsigned int cpt(0) ; cpt < NB_INSTRUCTION && !find ; ++cpt)
    {
      if(key.compare(tab_key[cpt]) == 0)
	{
	  find=true;
	  if(!verif_tab[cpt])
	    {
	      verif_tab[cpt]=true;
	      tab_information[cpt]=information;
	    }
	}
    }

  if(!find)
    cout << "ERROR " << key << " dont exist" << endl;
}

Send_Command Init_Config::get_cmd()
{
  return *send_cmd;
}

unsigned int Init_Config::convert_to_unsigned_int(string s)
{
  unsigned int r_s(0);

  for(unsigned int c=0 ; c < s.length() ; ++c)
    {
      switch(s[c])
	{
	case '0':
	  r_s+=0;
	  r_s*=10;
	  break;
	case '1':
	  r_s+=1;
	  r_s*=10;
	  break;
	case '2':
	  r_s+=2;
	  r_s*=10;
	  break;
	case '3':
	  r_s+=3;
	  r_s*=10;
	  break;
	case '4':
	  r_s+=4;
	  r_s*=10;
	  break;
	case '5':
	  r_s+=5;
	  r_s*=10;
	  break;
	case '6':
	  r_s+=6;
	  r_s*=10;
	  break;
	case '7':
	  r_s+=7;
	  r_s*=10;
	  break;
	case '8':
	  r_s+=8;
	  r_s*=10;
	  break;
	case '9':
	  r_s+=9;
	  r_s*=10;
	  break;
	}
    }

  return r_s/10;
}

Init_Config::~Init_Config()
{
  delete send_cmd;
}

int main(void)
{
  /*
  Init_Config i;

  i.get_cmd().send_bigtext("OK");
  i.get_cmd().stop_send();
  */

  Init_Admin* i=new Init_Admin();

  i->print_element();

  cout << "AFTER" << endl;

  delete i;
  i=NULL;

  return 0;
}
